package com.yjt.javatest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.javatest.dao.QuestionMapper;
import com.yjt.javatest.dao.QuestionTestLibMapper;
import com.yjt.javatest.dao.TestLibMapper;
import com.yjt.javatest.entity.Question;
import com.yjt.javatest.entity.QuestionTestLib;
import com.yjt.javatest.entity.TestLib;
import com.yjt.javatest.service.TestLibService;
import com.yjt.javatest.utils.APIResponse;
import com.yjt.javatest.utils.SecurityUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class TestLibServiceImpl extends ServiceImpl<TestLibMapper, TestLib> implements TestLibService {
    @Resource
    TestLibMapper testLibMapper;
    @Resource
    QuestionTestLibMapper questionTestLibMapper;
    @Resource
    QuestionMapper questionMapper;
    @Override
    public APIResponse getTestLibById(Long id) {
        TestLib testLib = testLibMapper.selectById(id);
        SecurityUtil.checkUserAuthority(testLib.getUserId());
        return APIResponse.success(testLib);
    }

    @Override
    public APIResponse createTestLib(TestLib testLib) {
        testLib.setUserId(SecurityUtil.getUserId());
        testLib.setIsDeleted(false);
        testLibMapper.insert(testLib);
        return APIResponse.success("创建成功");
    }

    @Override
    public APIResponse getTestLibsByUserId() {
        QueryWrapper<TestLib> wrapper = new QueryWrapper<>();
        wrapper .eq("user_id", SecurityUtil.getUserId())
                .eq("is_deleted", 0);
        List<TestLib> testLibs = testLibMapper.selectList(wrapper);
        return APIResponse.success(testLibs);
    }

    @Override
    public APIResponse updateTestLib(TestLib testLib) {
        TestLib testLib1 = testLibMapper.selectById(testLib.getId());
        if(Objects.isNull(testLib1)) {
            return APIResponse.error("试卷模板不存在！");
        }
        SecurityUtil.checkUserAuthority(testLib1.getUserId());
        testLibMapper.updateById(testLib);
        return APIResponse.success("修改成功");
    }

    @Override
    public APIResponse moveQuestionOrder(Long testLibId, Long questionId, Integer dir) {
        if(dir < 0 || dir > 1) {
            return APIResponse.error("dir参数值不正确！");
        }
        QueryWrapper<QuestionTestLib> wrapper = new QueryWrapper<>();
        QueryWrapper<QuestionTestLib> wrapper1 = new QueryWrapper<>();
        wrapper .eq("question_id", questionId)
                .eq("user_id", SecurityUtil.getUserId())
                .eq("test_id", testLibId);
        QuestionTestLib questionTestLib = questionTestLibMapper.selectOne(wrapper);
        wrapper1 .eq("user_id", SecurityUtil.getUserId())
                 .eq("test_id", testLibId)
                .last("limit 1");
        if(dir == 0) { //向上
            if(questionTestLib.getOrder() == 1) {
                return APIResponse.error("已经处于最上面");
            }
            wrapper1.lt("`order`", questionTestLib.getOrder());
        } else {
            if(Objects.equals(questionTestLib.getOrder(), questionTestLibMapper.getMaxOrderByTestLibId(testLibId))) {
                return APIResponse.error("已经处于最下面");
            }
            wrapper1.gt("`order`", questionTestLib.getOrder());
        }
        QuestionTestLib nextOne = questionTestLibMapper.selectOne(wrapper1);
        Long tempOrder = nextOne.getOrder();
        nextOne.setOrder(questionTestLib.getOrder());
        questionTestLib.setOrder(tempOrder);
        questionTestLibMapper.updateById(questionTestLib);
        questionTestLibMapper.updateById(nextOne);
        return APIResponse.success("移动成功");
    }

    @Override
    public APIResponse deleteQuestionFromTestLib(Long questionId, Long testLibId) {
        SecurityUtil.checkUserAuthority(testLibMapper.selectById(testLibId).getUserId());
        QueryWrapper<QuestionTestLib> wrapper = new QueryWrapper<>();
        wrapper .eq("test_lib_id", testLibId)
                .eq("question_id", questionId);
        questionTestLibMapper.delete(wrapper);
        return APIResponse.success("删除成功");
    }

    @Override
    public APIResponse deleteTestLib(Long testLibId) {
        TestLib testLib = testLibMapper.selectById(testLibId);
        SecurityUtil.checkUserAuthority(testLib.getUserId());
        testLibMapper.deleteById(testLibId);
        return APIResponse.success("删除成功");
    }

    @Override
    public APIResponse getQuestionIdsByTestLibId(Long testLibId) {
        QueryWrapper<QuestionTestLib> wrapper = new QueryWrapper<>();
        wrapper .eq("test_lib_id", testLibId)
                .orderByAsc("`order`");
        List<QuestionTestLib> questionTestLibs = questionTestLibMapper.selectList(wrapper);
        List<Long> ids = new ArrayList<>();
        for (QuestionTestLib questionTestLib : questionTestLibs) {
            ids.add(questionTestLib.getQuestionId());
        }
        return APIResponse.success(ids);
    }

    @Override
    public APIResponse getQuestionListByTestLibId(Long testLibId) {
        QueryWrapper<QuestionTestLib> wrapper = new QueryWrapper<>();
        wrapper .eq("test_lib_id", testLibId)
                .orderByAsc("`order`");
        List<QuestionTestLib> questionTestLibs = questionTestLibMapper.selectList(wrapper);
        List<Long> ids = new ArrayList<>();
        for (QuestionTestLib questionTestLib : questionTestLibs) {
            ids.add(questionTestLib.getQuestionId());
        }
        QueryWrapper<Question> wrapper1 = new QueryWrapper<>();
        if(ids.isEmpty()) {
            return APIResponse.success(null);
        }
        wrapper1.in("question_id", ids);
        List<Question> questions = questionMapper.selectList(wrapper1);
        return APIResponse.success(questions);
    }

    @Override
    public APIResponse addQuestionToTestLib(QuestionTestLib questionInfo) {
        Question question = questionMapper.selectById(questionInfo.getQuestionId());
        if(Objects.isNull(question)) {
            return APIResponse.error("题目不存在！");
        }
        TestLib testLib = testLibMapper.selectById(questionInfo.getTestLibId());
        if(Objects.isNull(testLib)) {
            return APIResponse.error("试卷模板不存在！");
        }
        SecurityUtil.checkUserAuthority(question.getUserId());
        SecurityUtil.checkUserAuthority(testLib.getUserId());
        if(Objects.isNull(questionInfo.getScore())) {
            return APIResponse.error("分数不能为空！");
        }
        if(questionInfo.getScore().compareTo(0) <= 0) {
            return APIResponse.error("分数不能<=0!");
        }
        questionInfo.setId(null);
        if(Objects.nonNull(questionInfo.getOrder())) {
            QueryWrapper<QuestionTestLib> wrapper = new QueryWrapper<>();
            wrapper .eq("`order`", questionInfo.getOrder())
                    .eq("test_lib_id", questionInfo.getTestLibId());

            if (Objects.nonNull(questionTestLibMapper.selectOne(wrapper))) {
                return APIResponse.error("order不能重复");
            }
        } else {
            questionInfo.setOrder(questionTestLibMapper.getMaxOrderByTestLibId(questionInfo.getTestLibId()) + 1);
        }
        questionTestLibMapper.insert(questionInfo);
        return APIResponse.success("添加成功");
    }
}
